package com.fourth.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.fourth.entity.Cart;
import com.fourth.entity.CartItem;
import com.fourth.entity.Goods;
import com.fourth.service.CartItemService;
import com.fourth.service.CartService;
import com.fourth.service.GoodsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @author 林奇伟
 */
@RestController
public class GoodsController {

    @Resource
    private GoodsService goodsService;
    @Resource
    private CartService cartService;
    @Resource
    private CartItemService cartItemService;

    /**
     * 获取所有商品方法
     * @return List<Goods>
     */
    @GetMapping("/selectAllGoods")
    public List<Goods> selectAllGoods(HttpServletResponse resp){
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "*");
        return goodsService.selectAllGoods();
    }

    /**
     * 非登录状态 - 添加商品到购物车方法
     * @param request
     */
    @GetMapping("/noLoginAddCart")
    public void noLoginAddCart(HttpServletRequest request,
                               HttpServletResponse response,
                               HttpSession session) throws IOException {
        //解决跨域问题
        setResponseHeader(response);

        //获取前端页面请求的参数
        String goodsId = request.getParameter("goodsId").trim();

        //获取购物车所有商品（Session域购物车）
        List<Cart> sessionCart = (ArrayList<Cart>) session.getAttribute("myCart");

        //获取购物车状态
        String cartState = (String) session.getAttribute("CartState");

        //初次拉取购物车为空
        if ("empty".equals(cartState)){

            //一条新的购物车记录
            Cart cart = new Cart();
            cart.setGoodId(goodsId);
            cart.setNum(1);
            cart.setUId(0);
            cart.setCreateTime(new Date());

            List<Cart> newSessionCart = new ArrayList<>();
            //往购物车添加新的商品
            newSessionCart.add(cart);

            //将更改数据后的购物侧添加到session
            session.setAttribute("myCart",newSessionCart);
            session.setAttribute("CartState","noEmpty");

            return;

        }else if (!"empty".equals(cartState)){

            if (sessionCart==null){
                //防止意外清除Session带来的异常
                response.sendRedirect("/goToIndex");
                return ;
            }

            //查询有无存在商品：（true）存在->添加数量  （false）不存在->添加对象
            boolean f = false;
            for (Cart cart : sessionCart) {
                if (goodsId.equals(cart.getGoodId())){
                    f=true; } }

            if(f){
                //存在相同商品
                for (int i = 0; i < sessionCart.size(); i++) {
                    //已存在的商品
                    Cart cart = sessionCart.get(i);

                    if (goodsId.equals(cart.getGoodId())) {
                        //使存在的商品数量+1后，放到新的购物车中
                        cart.setNum(cart.getNum()+1);
                        //设置更改数据时间
                        cart.setUpdateTime(new Date());
                        break;
                    }
                }
                //将更改数据后的购物侧添加到session
                session.setAttribute("myCart",sessionCart);
            }else {
                //不存在相同商品//一条新的购物车记录
                Cart cart = new Cart();
                cart.setGoodId(goodsId);
                cart.setNum(1);
                cart.setUId(0);
                cart.setUpdateTime(new Date());

                //往购物车添加新的商品
                sessionCart.add(cart);

                //将更改数据后的购物侧添加到session
                session.setAttribute("myCart",sessionCart);
            }
        }
    }

    /**
     * 已登录状态 - 添加商品到购物车方法
     * @param request
     */
    @GetMapping("/inLoginAddCart")
    public void inLoginAddCart(HttpServletRequest request,
                               HttpServletResponse response,
                               HttpSession session) throws IOException {
        //解决跨域问题
        setResponseHeader(response);

        //获取购物车所有商品（Session域购物车）
        List<Cart> sessionCart = (ArrayList<Cart>) session.getAttribute("myCart2");

        //获取前端页面请求的参数
        String goodsId = request.getParameter("goodsId").trim();
        Integer uId = Integer.valueOf(request.getParameter("uId").trim());

        //防止意外清除Session带来的异常
        if (uId==0||goodsId==null){
            response.sendRedirect("/goToIndex");
            return ; }

        //根据用户id查询购物车内容
        List<Cart> cartlist = cartService.selectCartByUid(uId);

        if(cartlist==null||0==cartlist.size()){
            //该用户购物车没有内容
            Cart cart = new Cart();
            cart.setGoodId(goodsId);
            cart.setUId(uId);
            cart.setNum(1);
            cart.setCreateTime(new Date());
            //将新建的购物车条目插入到数据库中
            int i = cartService.insertCartItem(cart);

            if (i>0){
                //顺便保存一份记录到session
                List<Cart> newCarts = new ArrayList<>();
                newCarts.add(cart);
                session.setAttribute("myCart2",newCarts);
            }
        }else {
            boolean flag = false;
            for (Cart cart : cartlist) {
                if (goodsId.equals(cart.getGoodId())){
                    flag = true; } }

            if (flag){
                //购物车已存在的商品
                cartService.updateGoodsNum(uId,goodsId);

                //顺便保存一份记录到session
                if (sessionCart!=null){
                    for (Cart cart : sessionCart) {
                        if (goodsId.equals(cart.getGoodId())){
                            cart.setNum(cart.getNum()+1);
                            cart.setUpdateTime(new Date());
                        }
                    }
                    session.setAttribute("myCart2",sessionCart);
                }else {
                    //本地session若为空，则将sql的数据获取下来放session
                    List<Cart> cartlist3 = cartService.selectCartByUid(uId);
                    session.setAttribute("myCart2",cartlist3);
                }
            }else {
                Cart cart = new Cart();
                cart.setGoodId(goodsId);
                cart.setUId(uId);
                cart.setNum(1);
                cart.setCreateTime(new Date());

                //将新建的购物车条目插入到数据库中
                int i = cartService.insertCartItem(cart);
                if (i>0){

                    //顺便保存一份记录到session
                    if (sessionCart!=null){
                        sessionCart.add(cart);
                        session.setAttribute("myCart2",sessionCart);
                    }else {
                        List<Cart> cartlist3 = cartService.selectCartByUid(uId);
                        session.setAttribute("myCart2",cartlist3);
                    }
                }
            }
        }
    }

    /**
     * 跳转到首页
     * 设置购物车状态
     * @param session
     * @return
     */
    @GetMapping("/goToIndex")
    public ModelAndView goToIndex(HttpSession session){

        //获取session的购物车
        ArrayList<Cart> sessionCart = (ArrayList<Cart>) session.getAttribute("myCart");

        //获取购物车状态
        String cartState = (String) session.getAttribute("CartState");
        if (sessionCart==null){
            session.setAttribute("CartState","empty");
        }

        ModelAndView mav = new ModelAndView();
        mav.setViewName("index");
        return mav;
    }

    /**
     * 前后台session交互
     * 解决session无法在前端获取的问题
     * @param request
     * @param response
     * @param session
     * @return
     */
    @GetMapping("/getLoginInfo")
    public Object getLoginInfo(HttpServletRequest request,
                               HttpServletResponse response,
                               HttpSession session){
        //跨域问题
        setResponseHeader(response);

//        登录模拟测试数据
//        session.setAttribute("uName","张三");
//        session.setAttribute("uId",1);

        //获取后台Session
        String uName = (String) session.getAttribute("uName");
        Integer uId = (Integer) session.getAttribute("uId");

        //封装数据
        Map<String,Object> map = new HashMap<>();
        map.put("uName",uName);
        map.put("uId",uId);

        //转成JSON后返回
//        String jsonString = JSONUtils.toJSONString(map);
        return map;
    }


    /**
     * 将普通购物车对象集合 转成购物车详情条目
     * 并用于传递服务端session到前端的方法
     * @param request
     * @param response
     * @param session
     * @return
     */
    @GetMapping("/getCartInfo")
    public List<CartItem> getCartInfo(HttpServletRequest request,
                                      HttpServletResponse response,
                                      HttpSession session){

        //获取登录状态
        Map<String, Object> info = getLoginStateAndInfo(request, response, session);
        boolean loginState = (boolean) info.get("loginState");
        Integer uId = (Integer) info.get("uId");


        if (loginState){

            List<CartItem> cartItems = cartItemService.selectCartItemByUid(uId);

            return cartItems;

        }else {

            List<CartItem> cartItems = new ArrayList<>();

            List<Cart> myCart = (List<Cart>) session.getAttribute("myCart");

            if (myCart==null||0==myCart.size()){
                CartItem cartItem = new CartItem();
                cartItems.add(cartItem);
                return cartItems;
            }

            for (Cart cart : myCart) {
                Goods goods = goodsService.selectGoodsById(Integer.valueOf(cart.getGoodId()));
                CartItem cartItem = new CartItem();
                //当前是未登录状态，uId为0或者null
                cartItem.setUId(cart.getUId());
                cartItem.setGoodsId(cart.getGoodId());
                cartItem.setId(cart.getId());
                cartItem.setPrice(goods.getPrice());
                cartItem.setStockNum(goods.getStockNum());
                cartItem.setStatus(goods.getStatus());
                cartItem.setDescription(goods.getDescription());
                cartItem.setSmallPic(goods.getSmallPic());
                cartItem.setTitle(goods.getTitle());
                cartItem.setItemId(goods.getItemId());
                cartItem.setUpdateTime(cart.getUpdateTime());
                cartItem.setNum(cart.getNum());
                cartItem.setUpdateTime(cart.getUpdateTime());
                cartItems.add(cartItem);
            }
            return cartItems;
        }
    }

    /**
     * 根据服务端session决定登录状态 提供id和name
     * @param request
     * @param response
     * @param session
     * @return 登录状态 uId uName
     */
    public static Map<String,Object> getLoginStateAndInfo(HttpServletRequest request,
                                                          HttpServletResponse response,
                                                          HttpSession session){
        //获取登录状态
        String uName = (String) session.getAttribute("uName");
        Integer uId = (Integer) session.getAttribute("uId");

        boolean loginState = false;
        if (uName==null||"".equals(uName)||0==uId||uId==null){
            loginState=false;
        }else if (uName!=null||!uName.equals("")){
            loginState=true;
        }

        if(loginState){
            System.out.println("当前登录状态：已登录，用户名="+uName+",ID="+uId);
        }else {
            System.out.println("当前登录状态：未登录，用户名="+uName+",ID="+uId);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("loginState",loginState);
        map.put("uId",uId);
        map.put("uName",uName);
        return map;
    }



    /**
     * 解决跨域问题
     * @param response
     */
    public static void setResponseHeader(HttpServletResponse response){
        //解决跨域问题
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
    }
}